package com.yootk.config;

import jakarta.persistence.SharedCacheMode;
import org.hibernate.jpa.HibernatePersistenceProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaDialect;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;

import javax.sql.DataSource;

@Configuration
@PropertySource("classpath:config/jpa.properties")
public class SpringDataJPAConfig {
    @Value("${hibernate.hbm2ddl.auto}")
    private String hbm2ddlAuto ;
    @Value("${hibernate.show_sql}")
    private boolean showSql ;
    @Value("${hibernate.format_sql}")
    private  String formatSql ;
    @Value("${hibernate.cache.use_second_level_cache}")
    private boolean secondLevelCache ;
    @Value("${hibernate.cache.region.factory_class}")
    private String factoryClass ;
    @Value("${hibernate.javax.cache.provider}")
    private String cacheProvider ;
    @Bean("entityManagerFactory")
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(
            DataSource dataSource,
            HibernatePersistenceProvider provider,
            HibernateJpaVendorAdapter adapter,
            HibernateJpaDialect dialect){
        LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean() ;
        factoryBean.setDataSource(dataSource);
        factoryBean.setPersistenceProvider(provider);
        factoryBean.setJpaVendorAdapter(adapter);
        factoryBean.setJpaDialect(dialect);
        factoryBean.setSharedCacheMode(SharedCacheMode.ENABLE_SELECTIVE);
        factoryBean.setPackagesToScan("com.yootk.po");
        factoryBean.setPersistenceUnitName("YootkJPA");
        factoryBean.getJpaPropertyMap().put("hibernate.hbm2ddl.auto",this.hbm2ddlAuto) ;
        factoryBean.getJpaPropertyMap().put("hibernate.format_sql",this.formatSql) ;
        factoryBean.getJpaPropertyMap().put("hibernate.cache.use_second_level_cache",this.secondLevelCache) ;
        factoryBean.getJpaPropertyMap().put("hibernate.cache.region.factory_class",this.factoryClass) ;
        factoryBean.getJpaPropertyMap().put("hibernate.javax.cache.provider",this.cacheProvider) ;
        return factoryBean ;
    }
    @Bean
    public HibernatePersistenceProvider provider(){
        return new HibernatePersistenceProvider() ;
    }
    @Bean
    public HibernateJpaVendorAdapter adapter(){
        HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter() ;
        adapter.setShowSql(this.showSql);
        return adapter ;
    }
    @Bean
    public HibernateJpaDialect dialect(){
        return new HibernateJpaDialect() ;
    }

}
